package com.darrenchan.leetcode;

import java.util.Stack;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2020-03-09 15:33
 */
public class Q394 {
    int index = 0;

    //s = "3[a2[c]]", 返回 "accaccacc".
    public String decodeString(String s) {
        StringBuilder sb = new StringBuilder();
        int num = 0;

        while (index < s.length()) {
            if (Character.isDigit(s.charAt(index))) {
                num = num * 10 + s.charAt(index) - '0';
                index++;
            } else if (s.charAt(index) == '[') {
                index++;
                System.out.println(num);
                String sub = decodeString(s);
                for (int i = 0; i < num; i++) {
                    sb.append(sub);
                }
                num = 0;
            } else if (s.charAt(index) == ']') {
                index++;
                return sb.toString();
            } else {
                sb.append(s.charAt(index));
                index++;
            }
        }

        return sb.toString();
    }

    //abc3[a]
    //4[ac]dy
    public String decodeString2(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            StringBuilder sb = new StringBuilder();
            if (s.charAt(i) != ']') {
                stack.push(s.charAt(i));
                continue;
            }
            while (!stack.isEmpty() && stack.peek() != '[') {
                sb.insert(0, stack.pop());
            }
            //跳过'['
            stack.pop();

            int num = 0;
            int unit = 1;
            while (!stack.isEmpty() && Character.isDigit(stack.peek())) {
                num += (stack.pop() - '0') * unit;
                unit *= 10;
            }

            if(num == 0) {
                sb.delete(0, sb.length());
            } else {
                String sub = sb.toString();
                for (int j = 0; j < num - 1; j++) {
                    sb.insert(0, sub);
                }
            }

            String subRepeat = sb.toString();
            for (int j = 0; j < subRepeat.length(); j++) {
                stack.push(subRepeat.charAt(j));
            }

        }

        StringBuilder res = new StringBuilder();
        while (!stack.isEmpty()) {
            res.insert(0, stack.pop());
        }

        return res.toString();
    }

    public static void main(String[] args) {
        System.out.println(new Q394().decodeString2("sdf3[ax0[cd]]tt"));
    }
}
